from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from datetime import timedelta

from app.database.base import get_db
from app.schemas.user import UserCreate, UserResponse, Token, UserUpdate
from app.services.user import UserService
from app.core.auth import authenticate_user, get_current_user
from app.core.security import create_access_token, verify_password, get_password_hash
from app.core.config import settings
from app.models.user import User

router = APIRouter(prefix="/auth", tags=["authentication"])
user_service = UserService()

@router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def register(
    user_data: UserCreate,
    db: Session = Depends(get_db)
):
    """用户注册"""
    # 检查用户名是否已存在
    existing_user = user_service.get_by_username(db, username=user_data.username)
    if existing_user:
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    # 检查邮箱是否已存在
    existing_email = user_service.get_by_email(db, email=user_data.email)
    if existing_email:
        raise HTTPException(status_code=400, detail="邮箱已存在")
    
    return user_service.create(db, obj_in=user_data)

@router.post("/login", response_model=Token)
async def login(
    form_data: OAuth2PasswordRequestForm = Depends(),
    db: Session = Depends(get_db)
):
    """用户登录"""
    user = authenticate_user(db, username=form_data.username, password=form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    
    return {
        "access_token": access_token,
        "token_type": "bearer",
        "user": UserResponse.from_orm(user)
    }


@router.get("/me", response_model=UserResponse)
async def get_current_user_info(
    current_user: User = Depends(get_current_user)
):
    """获取当前用户信息"""
    return current_user


@router.get("/verify", response_model=UserResponse)
async def verify_token(
    current_user: User = Depends(get_current_user)
):
    """验证token有效性"""
    return current_user


@router.put("/profile", response_model=UserResponse)
async def update_profile(
    user_update: UserUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新用户信息"""
    # 检查邮箱是否被其他用户使用
    if user_update.email and user_update.email != current_user.email:
        existing_email = user_service.get_by_email(db, email=user_update.email)
        if existing_email and existing_email.id != current_user.id:
            raise HTTPException(status_code=400, detail="邮箱已被其他用户使用")
    
    return user_service.update(db, db_obj=current_user, obj_in=user_update)


@router.post("/change-password")
async def change_password(
    current_password: str,
    new_password: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """修改密码"""
    # 验证当前密码
    if not verify_password(current_password, str(current_user.password_hash)):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="当前密码错误"
        )
    
    # 更新密码
    hashed_password = get_password_hash(new_password)
    user_service.update(db, db_obj=current_user, obj_in={"password_hash": hashed_password})
    
    return {"message": "密码修改成功"}


@router.post("/logout")
async def logout(
    current_user: User = Depends(get_current_user)
):
    """退出登录（客户端处理）"""
    return {"message": "退出成功"}